<?php
class VisitAction extends Action{
	
	
	function task() {
		$ret = array();
		$userModel = D('User');
		$username = $_REQUEST['sellername'];
		$checkName = $userModel->checkName($username);
		$userInfo = $userModel->getUserId($username,TRUE===$checkName);
		if (TRUE !==$checkName) {
			$ret['msg'] = $checkName;
		}elseif(!$userInfo){
			$ret['msg'] = array('images/notification.png','今天免费试用名额已经用完','明天再来吧！');
		}elseif ($userInfo['usr_timeout']<time()) {
			//到期
			if (1==$userInfo['usr_type']) {
				$ret['msg'] = array('images/notification.png','您的服务到期','亲您的服务已经到期，请续费！');
			}else {
				$ret['msg'] = array('images/notification.png','试用结束','试用已经结束，如果亲认为我们的软件很赞，请购买支持我们！');
			}
		}elseif (1==$userInfo['usr_type'] && $userInfo['usr_pw']!=$userModel->encrypt($_REQUEST['password']) && false) {
			//验证码错误
			$ret['errno'] = 1;
			$ret['msg'] = array('images/notification.png','服务验证码错误','请重新输入服务验证码！');
		}elseif (empty($_REQUEST['keywordName'])){
			$ret['msg'] = array('images/notification.png','请输入宝贝搜索关键字','请输入宝贝搜索关键字！');
		}else {
			$todayTime = strtotime(date('Y-m-d 0:0:0'));
			$uid 	=	$userInfo['usr_id'];
			$logModel = D('Log');
			$agentModel = D('Agent');
				
			$usedIps = $logModel->where("usr_id=$uid and log_datetime > $todayTime")->getField('log_id,agt_ip');//已经使用过的IP
			//付费用户每天200个限制，试用用户100个每天
			$payed = $userModel->getProperty($userInfo['usr_property'],'pay');
			if (count($usedIps)>100 && !$payed) {
				$ret['msg'] = array('images/notification.png','踩流量已经达到今日上限','今天的流量已经踩完，明天再来吧！');
			}
			if (isset($_GET['debug'])) {
				var_dump($payed);
			}
		}
		if (empty($ret['msg'])) {
			$keywords = array();
			foreach ($_REQUEST['keywordName'] as $i =>$v){
				if ($v) {
					$keywords[] = array(
							'name'=>$v,
							'cnt'=>$_REQUEST['keywordCnt'][$i]
					);
				}
			}
			if ($keywords) {
				shuffle($keywords);
				$completed = true;//所有任务已经完成
				foreach($keywords as $keyword){
					$cnt = $logModel->where(array(
							'usr_id' => $uid,
							'kw_name' => $keyword['name'],
							'log_page' => array('gt',0),
							'log_datetime' => array('gt',$todayTime),
					))->count();
					
					$notFindCnt = $logModel->where(array(
							'usr_id' => $uid,
							'kw_name' => $keyword['name'],
							'log_page' => -1,
							'log_datetime' => array('gt',$todayTime),
					))->count(); 
					if(0==$cnt && $notFindCnt>5){
						//没有找到
						$ret['msg'] = array('images/notification.png','关键词未找到',"关键词“{$keyword['name']}”未找到，请更换关键词。");
						continue;
					}
			   
					//这个关键词还没有搜索次还没到，分配代理IP
					if($cnt < $keyword['cnt']){
						$completed = false;
						$sql = "agt_rank in (1,2,3) and agt_country='中国' and agt_province not in ('台湾','香港','澳门') and agt_err=0";
						if($usedIps){
							//$sql .= sprintf(' AND agt_ip not in ("%s")',implode('","',$usedIps));//这样sql语句会过长，导致执行失败
							$sql .= sprintf(" AND agt_ip not in (SELECT agt_ip FROM %s WHERE usr_id='$uid' AND log_datetime> $todayTime)",$logModel->getTableName());
						}
						$ipInfo = $agentModel->where($sql)
						->order('rand()')
						->find();
						if($ipInfo){
							$ret	=array_merge($ret,array(
									'proxy'	=>array(
											'scheme'=>	strtolower($ipInfo['agt_type']),
											'host'=> $ipInfo['agt_ip'],
											'port'=>	intval($ipInfo['agt_port']),
									),
									'keyword'	=> $keyword['name'],
									'sellername'=>$username,
							));
							$logModel->add(array(
									'usr_id'	=>$uid,
									'agt_ip'	=> $ipInfo['agt_ip'],
									'kw_name'	=> $keyword['name'],
									'log_datetime'	=>	time(),
							));
							if (empty($usedIps)) {
								$ret['msg'] = array('images/notification.png','开始踩流量了','奴家开始踩流量了！');
							}
						}else {
							$ret['msg'] = array('images/notification.png','今天已经达到流量上限','重新启动流量软件再试！');
							if ($this->clearErr($uid)) {
								$this->task();
								exit();
							}
							
							
						}
						break;
					}
				}
				if ($completed) {
					$ret['msg'] = array('images/notification.png','今天流量已经踩完','如果还想踩流量，请增加宝贝搜索关键词或增加搜索次数');
				}
			}else {
				$ret['msg'] = array('images/notification.png','请输入宝贝搜索关键字','请输入宝贝搜索关键字！');
			}
	
		}
		//if(isset($ret['msg'])){
		exit(json_encode($ret));
		//}
	
	}
	
	/**
	 * @param integer $sellerId 用户ID
	 * @return boolean 是否可以删除
	 */
	private function clearErr($sellerId) {
		$cacheKey = $sellerId.date('Ymd');
		$value = S($cacheKey);
		$delPage = 0;
		if ($value || 0===$value) {
			$delPage = $value-1;
		}
		if ($delPage<-2) {
			return FALSE;
		}else {
			D('Log')->where(array(
				'usr_id'=>$sellerId,
				'log_page'=>$delPage,
				'log_datetime'=>array('gt',strtotime(date('Y-m-d 0:0:0')))
			))->delete();
			S($cacheKey,$delPage);
			return TRUE;
		}
	}
	
	function setPage() {
		$user = D('User')->getUserId($_REQUEST['sellername'],FALSE);
		if ($user) {
			$where = array('usr_id'=>$user['usr_id']);
			if (isset($_REQUEST['host'])) {
				$where['agt_ip'] = $_REQUEST['host'];
			}
			$lastLog = D('Log')->where($where)->order('log_datetime DESC')->find();
			if ($lastLog and 0==$lastLog['log_page']) {
				$findPage = $_REQUEST['page'];
				$lastLog['log_page'] = $findPage;
				D('Log')->save($lastLog);
				//如果页码大于2，说明是正常的。
				if ($findPage>-2) {
					D('Agent')->pageAlive($_REQUEST);
				}
				echo json_encode(1);
			}
		}
	}
	
	function getpercent() {
		$user = D('User')->getUserId($_REQUEST['sellername'],FALSE);
		if ($user) {
			$todayTime = strtotime(date('Y-m-d 0:0:0'));
			$lists = D('Log')->where(array('usr_id'=>$user['usr_id'],'log_page'=>array('gt',0),'log_datetime'=>array('gt',$todayTime)))->group('kw_name')->getField('kw_name,count(*)');
			echo json_encode($lists);
		}
	}
}